﻿/*******
 *    刷新令牌类使用ConcurrentDictionary存储key
 *    POST          http://localhost:9000/token
 *    Header        Content-Type: application/x-www-form-urlencoded
 *    Request Body  grant_type=refresh_token&refresh_token=refreshtokenid
 * *****/



namespace aier.wx.api.selfhost
{
    using Microsoft.Owin.Security.Infrastructure;
    using System;
    using System.Collections.Concurrent;

    public class RefreshAuthorizationTokenProvider : AuthenticationTokenProvider
    {
        private static ConcurrentDictionary<string, string> _refreshTokens = new ConcurrentDictionary<string, string>();

        public override void Create(AuthenticationTokenCreateContext context)
        {
            string tokenValue = Guid.NewGuid().ToString("n");

            context.Ticket.Properties.IssuedUtc = DateTime.UtcNow;
            context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(60);

            _refreshTokens[tokenValue] = context.SerializeTicket();

            context.SetToken(tokenValue);
        }

        public override void Receive(AuthenticationTokenReceiveContext context)
        {
            string value;
            if (_refreshTokens.TryRemove(context.Token, out value))
            {
                context.DeserializeTicket(value);
            }
        }
    }
}
